package com.keai.service;

import com.alibaba.dubbo.config.annotation.Service;
import com.keai.dao.OrderSettingDao;
import com.keai.pojo.OrderSetting;
import com.keai.utils.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * @author 黑马程序员
 * @Company http://www.ithiema.com
 * @Version 1.0
 */
@Service
@Transactional
public class OrderSettingServiceImpl implements OrderSettingService {

    @Autowired
    OrderSettingDao orderSettingDao;

    /**
     * 0. 遍历集合
     * 1. 添加ordersetting之前，先判断该日期是否进行预约设置
     *      如果预约设置过，就修改预约设置
     *          修改预约设置：如果已预约人数是否大于可预约人数，不可修改，抛出异常
     *      没有预约设置， 添加预约设置
     * @param orderSettingList
     */
    @Override
    public void editOrderSettingList(List<OrderSetting> orderSettingList) {
        if(orderSettingList!= null && orderSettingList.size() > 0){
            for (OrderSetting orderSetting : orderSettingList) {
                //根据预约设置的日期查询数据库中的预约设置对象
                OrderSetting orderSettingDb = orderSettingDao.findByDate(orderSetting.getOrderDate());
                if(orderSettingDb == null){
                    //没有进行预约设置，直接添加
                    orderSettingDao.add(orderSetting);
                }else{
                    //已经进行预约设置，修改
                    //获取已预约人数
                    int reservations = orderSettingDb.getReservations();
                    //获取可预约人数
                    int number = orderSetting.getNumber();
                    //已预约人数大于可预约人数，抛出异常
                    if(reservations > number){
                        throw  new RuntimeException("已预约人数大于可预约人数，批量导入失败!!!!");
                    }
                    //已预约人数小于等于可预约人数，直接修改
                    else{
                        orderSettingDao.edit(orderSetting);
                    }
                }
            }
        }
    }

    @Override
    public List<OrderSetting> findByMonth(String month) {
        String firstDay = month + "-01";
        String lastDay = month + "-31";
        List<OrderSetting> orderSettingList = orderSettingDao.findOrderSettingsByDate(firstDay, lastDay);
        return orderSettingList;
    }

    @Override
    public void orderSettingClear() {

        try {
            String date = DateUtils.parseDate2String(new Date());
            orderSettingDao.orderSettingClear(date);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
